package com.css.bjdt_report.util;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonResult {

	public static final String OK = "200";
	public static final String FAIL = "500";

	private final Map<String, Object> map = new HashMap<String, Object>();

	public JsonResult() {
	}

	public static JsonResult make() {
		return new JsonResult();
	}

	public static JsonResult ok() {
		return make().set("code", OK);
	}

	public static JsonResult ok(String msg) {
		return ok().set("msg", msg);
	}

	public static JsonResult error() {
		return make().set("code", FAIL);
	}

	public static JsonResult error(String msg) {
		return error().set("msg", msg);
	}

	public JsonResult set(String key, Object value) {
		map.put(key, value);
		return this;
	}

	public JsonResult set(String k1, Object v1, String k2, Object v2) {
		set(k1, v1).set(k2, v2);
		return this;
	}

	public JsonResult set(String k1, Object v1, String k2, Object v2, String k3, Object v3) {
		set(k1, v1).set(k2, v2).set(k3, v3);
		return this;
	}

	public JsonResult putAll(Map<String, ?> m) {
		map.putAll(m);
		return this;
	}

	public Map<String, Object> toJson() {
		return map;
	}

	public Map<String, String[]> jsonToStringArray(String jsonString) throws JSONException {
		Map<String, String[]> mapStrArray = new HashMap<String, String[]>();
		String jsonStringNew = jsonString.substring(7, jsonString.length() - 1);
		JSONArray jsonarray = new JSONArray(jsonStringNew);
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonobj = jsonarray.getJSONObject(i);
			String key = jsonobj.getString("key");
			String values = jsonobj.getString("value").substring(1, jsonobj.getString("value").length() - 1);
			String[] strArray = values.split(",");
			mapStrArray.put(key, strArray);
		}
		return mapStrArray;
	}

	public Map<String, String> jsonToString(String jsonString) throws JSONException {
		Map<String, String> mapStrArray = new HashMap<String, String>();
		String jsonStringNew = jsonString.substring(7, jsonString.length() - 1);
		JSONArray jsonarray = new JSONArray(jsonStringNew);
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonobj = jsonarray.getJSONObject(i);
			String key = jsonobj.getString("key");
			String values = jsonobj.getString("value").substring(1, jsonobj.getString("value").length() - 1);
			mapStrArray.put(key, values);
		}
		return mapStrArray;
	}

}
